jQuery(document).ready(function($){
	
	$('a').click(function(e) {
		if ($(this).hasClass('grid')) {
			$('#list_wrap ul').removeClass('list').addClass('grid');
			$('#sidebars').hide();
			$('#list_wrap').hide();
			$('.pager').hide();
			$('#list_container').removeClass('grid_11').addClass('grid_16');
			$('#map_wrap').fadeIn('slow');
			

		    var latitude;
		    var longitude;
		    
		    function showDetails(name, link, image, tag, location){
		      $('#details').fadeIn('slow').html('<div id="deal_image"><a href="'+link+'"><img src="'+image+'" alt="'+name+'" /></a></div><div id="deal_data"><a href="'+link+'">'+name+'</a><p>'+location+'<a href="'+link+'" id="grab">GRAB</a></p></div><div class="clear"></div>');
		    }
		    
		      function uniqueArray(myarray){
		      //var vals = this;
		      var uniques = [];
		      for(var i=myarray.length;i--;){
		        var val = myarray[i];
		        if($.inArray( val, uniques )===-1){
		          uniques.unshift(val);
		        }
		      }
		      return uniques;
		     }
		   
		    function capitalise(str){
		        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
		    }


		    function populateMarkers(latitude, longitude){
		      
		      $.ajax({url:buzzr_wp_url+'/wp-content/plugins/buzzr_ajax_map/map_query.php', dataType:'json', data:{ lat: latitude, lng: longitude, radius: 10 }, success:function(json){

		        if(json.markers != 'none'){
		          
		          var options = '';
		          var options_array = new Array();
		          
		          $.each( json.markers, function(i, m) {
		  					//Sidebar Deals List                                               
		            $('#deals_map_wrap').append('<div id="'+m.title+'" class="deals '+m.sanitized_tag+'"><div class="image"><img src="'+m.image+'" /></div><div class="text"><a href="javascript:void();">' + m.title + '</a></div><div class="clear"></div></div>').fadeIn('slow');
		            
		            options_array[i] = m.sanitized_tag; // array of categories for dropdown
		  					
		            $('#map_canvas').gmap('addMarker', { 'animation': google.maps.Animation.DROP, 'position': new google.maps.LatLng(m.lat, m.lng), 'tag': m.sanitized_tag, 'title': m.title }, function(map,marker){  
		            
		              switch(m.tag)
		              {
		                case 'Shopping':
		                  marker.setIcon('http://buzzr.in/wp-content/themes/buzzr_960/img/maps/shopping.png');
		                  break;
		                case 'Services':
		                  marker.setIcon('http://buzzr.in/wp-content/themes/buzzr_960/img/maps/services.png');
		                  break;
		                case 'Restaurants & Clubs':
		                  marker.setIcon('http://buzzr.in/wp-content/themes/buzzr_960/img/maps/restaurant.png');
		                  break;
		                case 'Fashion':
		                  marker.setIcon('http://buzzr.in/wp-content/themes/buzzr_960/img/maps/fashion.png');
		                  break;
		                case 'Entertainment':
		                  marker.setIcon('http://buzzr.in/wp-content/themes/buzzr_960/img/maps/entertainment.png');
		                  break;
		                case 'Flowers & Gifts':
		                marker.setIcon('http://buzzr.in/wp-content/themes/buzzr_960/img/maps/gifts.png');
		                break;
		                case 'Health & Beauty':
		                marker.setIcon('http://buzzr.in/wp-content/themes/buzzr_960/img/maps/healthbeauty.png');
		                break;
		                default:
		                marker.setIcon('http://buzzr.in/wp-content/themes/buzzr_960/img/maps/gifts.png');
		                break;
		              }
		              
		              $(marker).click( function(event) {
		                showDetails(m.title, m.link, m.image, m.tag, m.location);
		                var _this = this;
		                this.setAnimation(google.maps.Animation.BOUNCE);
		                setTimeout(function() { _this.setAnimation('null') }, 1500);
		              });
		                
		  				  });
		  				  
		          });
		         
		         $('.deals').mouseover(function() {
		          $(this).css('background-color','#F3F3F3');
		        });
		    
		        $('.deals').mouseout(function() {
		          $(this).css('background-color','#FFFFFF');
		        });
		        
		        $('.deals').click(function() {
		          var marker_title = $(this).attr('id');
		            $('#map_canvas').gmap('findMarker', 'title', marker_title, function(found, marker_hover) {
		              if(found === true){
		                $(marker_hover).triggerEvent('click');
		                return false;
		              }
		            });
		        });
		         
		         var unique = uniqueArray(options_array);
		          options = '<option value="all">All</option>';
		          $.each( unique, function(i, category) {
		            options += '<option value="'+category+'">'+capitalise(category)+'</option>';
		          });
		          
		          $('#tags').html(options);
		          $('#tags-control').fadeIn('slow');
		          
		  			}else{
		          alert('Sorry no deals in this area, please drag further!');
		          $('#spinner').fadeOut('slow');
		        }
		  		}});
		    }
		    
		    var city_name = window.location.toString().split('/');
		    if(city_name.length >= 6){
		    	city_name = city_name[5];
		    }else{
		        city_name = 'mumbai';
		    }
		    
		    geocoder = new google.maps.Geocoder();
		  	geocoder.geocode( { 'address': city_name+',india'}, function(results, status) {
		  		var lat_lng = results[0].geometry.location;
		  		var latitude = results[0].geometry.location.lat();
		  		var longitude = results[0].geometry.location.lng();

		  		$('#map_canvas').gmap({ 'panControl': false, 'maxZoom': 19, 'center':lat_lng,'scrollwheel': true, 'streetViewControl': false,'mapTypeControl': false,'zoom': 11, 'callback': function(map) {

		  		populateMarkers(latitude, longitude);
		  		
		  		$(map).dragend( function(event) {
		  	      $('#map_canvas').gmap('clearMarkers');
		  	      $('#details').html('');
		          $('#tags').html('');
		          $('#tags-control').fadeOut('slow');
		          $('#deals_map_wrap').html('').fadeOut('slow');
		          
		          var lat_lng = map.getCenter();
		  		    var latitude = lat_lng.lat();
		  		    var longitude = lat_lng.lng();
		  		    
		  		    populateMarkers(latitude, longitude);
		  		    
		  	    });
		  	    
		  	    $('#map_canvas').gmap('addControl', 'tags-control', google.maps.ControlPosition.TOP_RIGHT);
		  	    $('#map_canvas').gmap('addControl', 'search', google.maps.ControlPosition.TOP_LEFT);
		      
		  		}});
		  	});

		    $("#address").focus(function (){
		      var value = $(this).val();
		      if(value == '(Area, City) or (City)'){
		      $(this).val('');
		      $(this).css({'color': 'black'});
		      }
		    });

		    $('#address').blur(function() {
		      var value = $(this).val();
		      if(value == ''){
		      $(this).css({'color': 'grey'});
		      $(this).val('(Area, City) or (City)');
		      }else{
		      
		      $('#address_go').click(function() {
		        $('#details').html('');
		        geocoder = new google.maps.Geocoder();
		  	    geocoder.geocode( { 'address': value+',india'}, function(results, status){
		        var lat_lng = results[0].geometry.location;
		    		var latitude = results[0].geometry.location.lat();
		    		var longitude = results[0].geometry.location.lng();
		  
		    		$('#map_canvas').gmap({ 'panControl': false, 'maxZoom': 19, 'center':lat_lng,'scrollwheel': true, 'streetViewControl': false,'mapTypeControl': false,'zoom': 11, 'callback': function(map) {
		          $('#map_canvas').gmap('clearMarkers');
		          $('#tags').html('');
		          $('#tags-control').fadeOut('slow');
		          $('#deals_map_wrap').html('').fadeOut('slow');
		    			populateMarkers(latitude, longitude);
		    		
		    			$(map).dragend( function(event) {
		    	      $('#map_canvas').gmap('clearMarkers');
		    	      $('#details').html('');
		            $('#tags').html('');
		            $('#tags-control').fadeOut('slow');
		            $('#deals_map_wrap').html('').fadeOut('slow');
		            var lat_lng = map.getCenter();
		    		    var latitude = lat_lng.lat();
		    		    var longitude = lat_lng.lng();
		    		    
		    		    populateMarkers(latitude, longitude);
		    		    
		    	    });
		    	    
		    		}});
		    		});
		  		
		  		});
		  		
		  		}
		  	});

		    $("#tags").change(function() {
						$('#details').html('');
		        var bounds = new google.maps.LatLngBounds();
						var tag = $(this).val();
						
						//Hide deals from Sidebar Deals List or Show based on dropdown selection
		        if(tag != 'all'){
		          $('.deals').fadeIn('slow');
		          $('.deals').not($('.'+tag)).fadeOut('slow');
		        }else{
		          $('.deals').fadeIn('slow');
		        }
						
		        if ( tag == 'all' ) {
							$('#map_canvas').gmap('findMarker', 'tag', tag, function(found, marker) {
								marker.setVisible(true); 
								bounds.extend(marker.position);
								marker.map.fitBounds(bounds);	
							});
						} else {
							$('#map_canvas').gmap('findMarker', 'tag', tag, function(found, marker) {
								if (found) {
									marker.setVisible(true); 
									bounds.extend(marker.position);
									marker.map.fitBounds(bounds);
								} else { 
									marker.setVisible(false); 
								}
							});
						}
						$('#map_canvas').gmap('option', 'center', bounds.getCenter());
				});
		    
		    
		    $('#spinner').ajaxStart(function(){
		       $(this).fadeIn('slow');
		    });
		    
		    $('#spinner').ajaxStop(function(){
		      $(this).fadeOut('slow');
		    });
			
			
			
		}
		else if($(this).hasClass('list')) {
			$('#list_wrap ul').removeClass('grid').addClass('list');
			$('#sidebars').show();
			$('#list_wrap').show();
			$('.pager').show();
			$('#list_container').removeClass('grid_16').addClass('grid_11');
			$('#map_wrap').fadeOut('slow');
		}
	});
    
    $('.social').css('display','none');
    
    $('.deal').mouseenter(function(){
    	$('.social',$(this)).css('display','block');
        $('.info',$(this)).css('background-color','#2589BC');
        $('.info_name',$(this)).css('color','#ffffff');
        $('.info_name a',$(this)).css('color','#ffffff');
    }).mouseleave(function(){
    	$('.social',$(this)).css('display','none');
    	$('.info',$(this)).css('background-color','#ffffff');
    	$('.info_name',$(this)).css('color','#000000');
    	$('.info_name a',$(this)).css('color','#000000');
    });
    
    $('.details').hide();
    
    $('.more').click(function(){
    	$(this).parent('.get_deal').siblings('.details').slideToggle(500);
    });
    
});